<?php
namespace dwc_app;

class GoogleSpreadsheetsAPI extends GoogleAPI
{
    static $service_name = 'wise';
    
    public function create_worksheet($table_name, $fields)
    {
        $spreadsheets = $this->get_spreadsheets();
        foreach($spreadsheets->entry as $entry)
        {
            if($entry->title == "DWCA Test")
            {
                $body = '<entry xmlns="http://www.w3.org/2005/Atom" xmlns:gs="http://schemas.google.com/spreadsheets/2006">
                        <title>'.$table_name.'</title>
                        <gs:rowCount>50</gs:rowCount>
                        <gs:colCount>50</gs:colCount>
                    </entry>';
                $headers = array(
                    "Content-length: " . strlen($body),
                    "Content-type: application/atom+xml",
                    "GData-Version: 3.0",
                    "Authorization: GoogleLogin auth=" . $this->auth_token . " ");
                $response = simplexml_load_string(http_post($entry->content['src'], $body, $headers));
                $id = $response->id;
                echo "<br><br>$id<br><br>";
                if(preg_match("/worksheets\/(.*?)\//", $id, $arr))
                {
                    $feed_id = $arr[1];
                    $body = '<entry xmlns="http://www.w3.org/2005/Atom"
                        xmlns:gs="http://schemas.google.com/spreadsheets/2006">
                      <title type="text">Taxa</title>
                      <summary type="text">DwCA taxa</summary>
                      <gs:worksheet name="'.$table_name.'" />
                      <gs:header row="1" />
                      <gs:data numRows="0" startRow="2">';
                    foreach($fields as $field_name)
                    {
                        static $char = 65;
                        $body .= "<gs:column index='".chr($char)."' name='$field_name' />";
                        $char++;
                    }
                    $body .= "</gs:data></entry>";
                    $headers = array(
                        "Content-length: " . strlen($body),
                        "Content-type: application/atom+xml",
                        "GData-Version: 3.0",
                        "Authorization: GoogleLogin auth=" . $this->auth_token . " ");
                    $response = simplexml_load_string(http_post("https://spreadsheets.google.com/feeds/$feed_id/tables", $body, $headers));
                    return (string) $response->id;
                }
            }
        }
        return false;
    }
    
    public function send_core_taxa_to_spreadsheets($feed_id, $fusion_table_fields)
    {
        $file_contents = get_remote_file($this->dwca->core->file_uri);
        $lines = explode($this->dwca->core->lines_terminated_by, $file_contents);
        
        $row_data = array();
        $line_num = 0;
        foreach($lines as $line)
        {
            $line_num++;
            if($this->dwca->core->ignore_header_lines && $line_num == 1) continue;
            if(!trim($line)) continue;
            $line = preg_replace("/^".preg_quote($this->dwca->core->fields_enclosed_by, "/")."/", "", $line);
            $line = preg_replace("/".preg_quote($this->dwca->core->fields_enclosed_by, "/")."$/", "", $line);
            $fields = explode($this->dwca->core->fields_enclosed_by.$this->dwca->core->fields_terminated_by.$this->dwca->core->fields_enclosed_by, $line);
            if($fields)
            {
                foreach($fields as $key => $value) $fields[$key] = str_replace("'", "\'", $value);
                $row_data[] = "INSERT INTO $table_id (". implode(", ", array_keys($fusion_table_fields)).") VALUES ('". implode("','", $fields) ."');";
            }
            if(count($row_data) >= 500)
            {
                echo "Inserting batch of 500<br>";
                flush();
                $this->fusion_tables_api->query(implode(" ", $row_data));
                $row_data = array();
                //break;
            }
        }
        if($row_data)
        {
            echo "Inserting remaining batch of ".count($row_data)."<br>";
            flush();
            $this->fusion_tables_api->query(implode(" ", $row_data));
            unset($row_data);
        }
    }
    
    public function create_record($table_feed_id, $body)
    {
        $headers = array(
            "Content-length: " . strlen($body),
            "Content-type: application/atom+xml",
            "GData-Version: 3.0",
            "Authorization: GoogleLogin auth=" . $this->auth_token . " ");
        //echo http_post($table_feed_id, $body, $headers);
        
        //echo("<br><br>php spreadsheets_insert_async.php $table_feed_id ".base64_encode(serialize($body))." ".base64_encode(serialize($headers)));
        shell_exec("php spreadsheets_insert_async.php $table_feed_id ".base64_encode(serialize($body))." ".base64_encode(serialize($headers))." > /dev/null 2>/dev/null &");
    }
    
    public function get_spreadsheets()
    {
        return simplexml_load_string(http_get('https://spreadsheets.google.com/feeds/spreadsheets/private/full', array('GData-Version: 3.0', "Authorization: GoogleLogin auth=" . $this->auth_token)));
    }
}

?>